﻿using System;
using System.Collections.Generic;
using System.IO;
using Docentric.Word;
using Docentric.Examples.Data.TypedDataSets;
using Docentric.Examples.Data.TypedDataSets.NorthwindDataSetTableAdapters;


namespace Docentric.Examples.Browser
{
	public class TypedDataSetExample : ExampleBase
	{
		// Constructor
		public TypedDataSetExample()
		{
			Name = "TypedDataSet";
			Title = "Typed Data Set";
			Description = "This example shows how to populate a report from a Typed Data Set which can be treated like any other .NET object/class. Here the default data source represents the 'Purchase Orders' Typed Data Table which is part of a Typed Data Set containing several interrelated Typed Data Tables. In order to also render all the detail items of each purchase order we had to manually add the 'Navigation' property to 'Purchase_Order_DetailsRow' partial class. (Running this exemple requires MS Access 2010)";
		}


		// GenerateReport
		public override string GenerateReport()
		{
			// Load all purchase orders from the Northwind database.
			NorthwindDataSet.Purchase_OrdersDataTable purchaseOrdersDataTable = DataAccess.LoadPurchaseOrders();

			// Create a temporary file for the generated report document.
			string reportDocumentFileName = System.IO.Path.GetTempPath() + "GeneratedReport_" + Guid.NewGuid().ToString() + ".docx";
			using (Stream reportDocumentStream = File.Create(reportDocumentFileName))
			{
				// Open the report template file.
				using (Stream reportTemplateStream = GetReportTemplate())
				{
					// Generate the report document using 'DocumentGenerator'.
					DocumentGenerator dg = new DocumentGenerator(purchaseOrdersDataTable);
					dg.ElementInitialize += new ElementInitializeHandler(dg_ElementInitialize);		// Hook to the 'ElementInitialize' in order to be able to provide values for unbound elements.
					DocumentGenerationResult result = dg.GenerateDocument(reportTemplateStream, reportDocumentStream);
					if (result.HasErrors)
					{
						foreach (Word.Error error in result.Errors) Console.Out.WriteLine(error.Message);
					}
				}
			}

			return reportDocumentFileName;
		}


		private void dg_ElementInitialize(object sender, ElementInitializeEventArgs e)
		{
			if (e.Element.Name == "FLD_TotalPrice")
			{
				// The current data context is an object of type 'NorthwindDataSet.Purchase_Order_DetailsRow'.
				NorthwindDataSet.Purchase_Order_DetailsRow currentPurchaseOrderDetail = (NorthwindDataSet.Purchase_Order_DetailsRow)e.Element.DataContext.Value;

				// Calculate the total price.
				e.Element.AsField().Value = currentPurchaseOrderDetail.Quantity * currentPurchaseOrderDetail.Unit_Cost;
			}
		}
	}
}
